<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Lib\Express;
use App\Models\ExpressType;
use App\Models\MallOrder;
use App\Models\MallOrderProduct;
use App\Services\MallOrderService;
use App\Services\MallRefundService;
use Illuminate\Http\Request;

class MallOrderController extends BaseController
{
    public function index(Request $request) {
        $input = $request->input();
        $search = ['status' => -1, 'order_sn' => '', 'start_at' => '', 'end_at' => ''];
        $phone = $request->input('phone');
        $contact = $request->input('contact');
        $title = $request->input('title');
        $list = MallOrder::withTrashed()->apply($search, $input)
            ->when($title, function ($q) use($title) {
                $q->whereHas('order_product.product', function ($qr) use($title) {
                    $qr->where('title', 'like', '%' . $title . '%');
                });
            })
            ->when($phone, function ($q) use($phone) {
                $q->whereHas('address', function ($qr) use($phone) {
                    $qr->where('phone', 'like', '%' . $phone . '%');
                });
            })
            ->when($contact, function ($q) use($contact) {
                $q->whereHas('address', function ($qr) use($contact) {
                    $qr->where('contact', 'like', '%' . $contact . '%');
                });
            })
            ->withCertain('order_product.product', ['title'])
            ->withCertain('address', ['contact', 'phone'])
            ->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }


    public function deliver(Request $request) {
        $this->validate($request, [
            'order_product_id' => 'required',
            'express_order_sn' => 'required',
            'express_id' => 'required',
        ]);
        $input = $request->input();
        $express = ExpressType::find($input['express_id']);
        if (!$express)
            return $this->failed('快递不存在');
        try {
            $input['express_id'] = $express->id;
            $input['express_title'] = $express->title;
            $input['order_product_id'] = json_decode($input['order_product_id'], true);
            $order_product_id = current($input['order_product_id']);
            $order_product = MallOrderProduct::find($order_product_id);
            if (!$order_product)
                return $this->failed('订单id不存在');
            $input['order_id'] = $order_product->order_id;
            MallOrderService::handle($input, 'deliver');
            return $this->success([], '发货成功');
        } catch (\Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    public function cancel(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
        ]);
        $input = $request->input();
        try {
            $input['close_type'] = MallOrder::CLOSE_TYPE_ADMIN;
            MallOrderService::handle($input, 'cancel');
            return $this->success([], '取消成功');
        } catch (\Exception $e) {
            return $this->failed($e->getMessage());
        }
    }

    public function info(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
        ]);
        $input = $request->input();

        $info = MallOrder::withTrashed()->withCertain('order_product.product', ['title'])
            ->withCertain('order_product_zero.product', ['title', 'image_url'])
            ->with('address')->find($input['order_id']);
        if (!$info)
            return $this->failed('订单号不存在');

        return $this->success($info);

    }

    public function expressInfo(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
        ]);
        $input = $request->input();
        $group_list = MallOrderProduct::where('order_id', $input['order_id'])->where('express_order_sn', '!=', '')
            ->select('express_order_sn')->groupBy('express_order_sn')->get();
        $list = [];
        foreach ($group_list as $key => $item) {
            $temp = [];
            $order_product_list = MallOrderProduct::where('order_id', $input['order_id'])
                ->where('express_order_sn', $item->express_order_sn)
                ->withCertain('product', ['title', 'video_url', 'image_url'])
                ->get();

            foreach ($order_product_list as  $key2 => $order_product) {
                $m = [
                    'id' => $key2 + 1,
                    'express_order_sn' => $order_product->express_order_sn,
                    'express_title' => $order_product->express_title,
                    'express_start_at' => $order_product->express_start_at,
                    'issign' => $order_product->issign,
                ];
                $temp['basic'] = $m;
                break;
            }

            $mt = [];
            foreach ($order_product_list as $key1 => $order_product) {
                $mt[] = [
                    'id' => $key1 + 1,
                    'title' => $order_product->product->title,
                    'buy_num' => $order_product->buy_num,
                    'image_url' => $order_product->product->image_url,
                    'video_url' => $order_product->product->video_url,
                    'issign' => $order_product->issign,
                    'paid_amount' => $order_product->paid_amount,
                ];
            }
            $temp['product'] = $mt;

            $first = current(Express::search($item->express_order_sn));
            $temp['express_latest'] = $first['status'] ?? '';
            $temp['id'] = $key +1;
            $list[] = $temp;
        }
        return $this->success($list);
    }

    public function editPrice(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
            'price_item' => 'required',
        ]);
        try {
            return \DB::transaction(function () use($request){
                $input = $request->input();
                $order = MallOrder::find($input['order_id']);
                if (!$order)
                    return $this->failed('订单号不存在');

                if ($order->status != MallOrder::STATUS_WAIT_PAY)
                    return $this->failed('当前订单状态不是待支付，无权修改');

                $total = $order->fare;

                $input['fare'] = $input['fare'] ?? 0;
                if ($input['fare'] < 0 )
                    return $this->failed('运费不能小于0');
                $fare = $input['fare'] * 100;
                if ($fare) {
                    if ($fare > $order->fare)
                        throw new \Exception('运费不能大于原运费价格');
                    $total -= $fare;
                    $order->fare = $fare;
                }

                $arr_price_item = json_decode($input['price_item'], true);
                foreach ($arr_price_item as $item) {
                    $model = MallOrderProduct::find($item['order_product_id']);
                    $model->paid_amount -= $item['value'] * 100;
                    if ($model->paid_amount < 0)
                        throw new \Exception('价格不能大于原价格');
                    $model->save();

                    $total += $model->paid_amount;
                }
                if  ($total <= 0)
                    return $this->failed('总金额必须大于0');
                $order->paid_amount = $total;
                $order->union_total_amount = $total;
                $order->save();

                return $this->success([], '修改成功');
            });

        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }

    }


    public function apply_refund(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
            'order_product_id' => 'required',
        ]);
        $input = $request->input();
        if ($input['order_id'] && !$input['order_product_id']) {
            $list = MallOrderProduct::where('order_id', $input['order_id'])->where('status', MallOrderProduct::STATUS_WAIT_PRODUCT)->get();
            if ($list) {
                foreach ($list as $key => $order_product) {

                    try {
                        \DB::beginTransaction();
                        $input['user_id'] = $order_product->user_id;
                        $input['order_product_id'] = $order_product->id;
                        $refund = MallOrderService::handle($input, 'refund', false);

                        //处理退款
                        $input['refund_id'] = $refund->id;
                        MallRefundService::handle($input, 'agree', false);
                        \DB::commit();
                    } catch (\Exception $e) {
                        \DB::rollBack();
                        \Log::error($e);
                        return $this->failed('退款失败：' . $e->getMessage());
                    }

                }
            }
        } else {
            try {
                $order_product = MallOrderProduct::find($input['order_product_id']);
                if (!$order_product)
                    return $this->failed('商品不存在');

                $input['user_id'] = $order_product->user_id;
                $input['order_id'] = $order_product->order_id;
                $refund = MallOrderService::handle($input, 'refund');

                //处理退款
                $input['refund_id'] = $refund->id;
                MallRefundService::handle($input, 'agree');

                \DB::commit();
            } catch (\Exception $e) {
                \DB::rollBack();
                \Log::error($e);
                return $this->failed($e->getMessage());
            }

        }
        return $this->success([], '退款成功');

    }

}

